from typing import Optional, List
from sqlmodel import Field, Relationship, SQLModel
from sqlalchemy import event, Column, Text
from enum import Enum

from models.Base import BaseAndTime , StatusTypeEnum
from models.common import get_current_time
from .Dept import Department
from .Link import Admin_Role_Link
class SexEnum(int, Enum):
    MAN = 0
    WUMEN = 1

class login(SQLModel):
    userName: str
    password: str
    verifyCode:str

class assign_params(SQLModel):
    id: int
    roleIds: List[int]


class refresh_token(SQLModel):
    refreshToken: str

# 登录返回
class login_result(SQLModel):
    roles: List[str]
    username: str
    nickname: str
    accessToken: str
    refreshToken: str
    expires: str
    avatar:str 

class create_admin(SQLModel):
    nickName: Optional[str] = Field(max_length=30,title='昵称')
    userName: str = Field(max_length=30,nullable=False,title='用户名',unique=True)
    password: str = Field(max_length=255,nullable=False,title='密码')
    avatar: Optional[str] = Field(max_length=255,nullable=False,title='头像')
    mobile: str = Field(
        default="15038301671",
        regex=r"^1[3-9]\d{9}$",  # 正则表达式验证中国大陆手机号格式
        description="A valid Chinese mobile number, starting with 13-19 and 11 digits in length."
    )
    email: Optional[str] = Field(max_length=255,nullable=False,title='邮箱')
    avatar: Optional[str] = ""
    department_id:int 
    sex: SexEnum = Field(sa_column_kwargs={"nullable": False},default=SexEnum.MAN, title='性别', index=True,description="0:男 1:女")
    status: StatusTypeEnum = Field(sa_column_kwargs={"nullable": False},default=StatusTypeEnum.NORMAL, title='状态', index=True,description="0:正常 1:关闭")
    remark: Optional[str] = Field(max_length=255,nullable=False,title='备注')

class edit_admin(SQLModel):
    id: int = 1
    nickName: Optional[str] = Field(max_length=30,title='昵称')
    avatar: Optional[str] = Field(max_length=255,nullable=False,title='头像')
    mobile: str = Field(
        default="15038301671",
        regex=r"^1[3-9]\d{9}$",  # 正则表达式验证中国大陆手机号格式
        description="A valid Chinese mobile number, starting with 13-19 and 11 digits in length."
    )
    avatar: Optional[str] = ""
    department_id:Optional[int] = 0
    status: Optional[StatusTypeEnum] = Field(sa_column_kwargs={"nullable": False},default=StatusTypeEnum.NORMAL, title='状态', index=True,description="0:正常 1:关闭")
    password: Optional[str] = Field(sa_column_kwargs={"nullable": False},default=None,title='密码')

# 管理员
class Admin(BaseAndTime,create_admin, table=True):
    __tablename__ = "sys_admin"  # 确保表名一致
    logintime: Optional[int] = Field(default=get_current_time(),title='登录时间')
    loginip:  Optional[str] = Field(max_length=30,title='登录ip')
    roles: List["Role"] = Relationship(back_populates="admins", link_model=Admin_Role_Link)
    department_id:int | None = Field(default=None, foreign_key="sys_department.id")
    department: Department = Relationship(back_populates="admins")

    @property
    def status_text(self)->str:
        if self.status == StatusTypeEnum.NORMAL:
            return "正常"
        elif self.status == StatusTypeEnum.ABNORMAL:
            return "关闭"
        return "未知"
    
# 管理员记录
class Admin_Record(BaseAndTime,table=True):
    __tablename__ = "sys_admin_record"  # 确保表名一致
    id: int = Field(default=None, primary_key=True)
    admin_id: Optional[int] = Field(nullable=False, foreign_key="sys_admin.id")
    username: str = Field(nullable=False,title='管理员名称')
    action: str = Field(nullable=False,title='方法')
    auth: str = Field(nullable=False,   title='权限')
    path: str = Field(nullable=False,title='路径')
    ip_address: str = Field(max_length=30,nullable=False,title='ip')
    os: str = Field(max_length=30,nullable=False,title='操作系统')
    browser: str = Field(max_length=30,nullable=False,title='浏览器')
    message: str = Field(max_length=255,nullable=False,title='错误信息')


# 登录日志
class Admin_Login_Record(SQLModel,table=True):
    __tablename__ = "sys_admin_login_record"  # 确保表名一致
    id: Optional[int] = Field(default=None, primary_key=True)
    admin_id: Optional[int] = Field(nullable=False, foreign_key="sys_admin.id")
    admin_name: str = Field(nullable=False,title='管理员名称')
    ip: str = Field(max_length=30,nullable=False,title='ip')
    useragent: str = Field(nullable=False,title='useragent')
    status: StatusTypeEnum = Field(sa_column_kwargs={"nullable": False},default=StatusTypeEnum.NORMAL, title='登录状态', index=True,description="0:成功 1:失败")
    channels: str = Field(max_length=30,nullable=False,title='渠道')
    # desc 字段设置为text类型，不限制长度
    desc: str = Field(sa_column=Column(Text, nullable=False), title="详细内容")
    createtime:  Optional[int] = Field(default=get_current_time(), nullable=False,title='创建时间')

    @property
    def status_text(self)->str:
        if self.status == StatusTypeEnum.NORMAL:
            return "正常"
        elif self.status == StatusTypeEnum.ABNORMAL:
            return "关闭"
        return "未知"


@event.listens_for(Admin, 'before_update', propagate=True)
def timestamp_before_update(mapper, connection, target):
    target.updatetime = get_current_time()


# 默认weight设置为id
# @event.listens_for(admin, "after_insert")
# def receive_after_insert(mapper, connection, target):
#     target.weight = target.id
        

class redis_admin(SQLModel):
    admin_ids: List[int]
    admin: Admin